package com.cn.qgx428.lazydiary.local

import android.annotation.TargetApi
import android.os.Build
import android.support.annotation.RequiresApi
import android.text.TextUtils
import java.util.concurrent.ConcurrentHashMap

/**
 * Created by qinguanxiong on 2018/1/14.
 */
class LManager private constructor(){

    companion object {
        val instance = LManager()
        var works : MutableMap<LActionWacher, MutableList<String>> = ConcurrentHashMap<LActionWacher,MutableList<String>>()
        fun newInstance() = instance
    }

    private val emptyMessege = LAMessege()

    fun register(watcher: LActionWacher, action:String){
        if (works.contains(watcher)){
            var actions = works.get(watcher) as MutableList<String>
            actions.add(action)
        } else{
            var actions = mutableListOf<String>()
            actions.add(action)
            works.put(watcher, actions)
        }
    }

    @Synchronized fun unRegister(watcher: LActionWacher){
        works.remove(watcher)
    }


    fun trigger(action: String, msg: LAMessege = emptyMessege){
        if (TextUtils.isEmpty(action))
            return
        works.keys.forEach {
            val worker = it
            works.get(it)?.forEach {
                if (it.equals(action)){
                    worker.onTrigger(action, msg)
                }
            }
        }
    }
}

